package processes

import (
	"encoding/json"
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/constants"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/message"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/netWork"
)

// ShowMenu 显示登陆成功后的页面
func ShowMenu() {
	var loop = true
	for loop {
		fmt.Printf("\t\t\t欢迎用户%s(ID:%d)\t\t\t\n", curUser.UserName, curUser.UserId)
		fmt.Println("\t\t\t\t1 显示在线用户列表")
		fmt.Println("\t\t\t\t2 发送信息")
		fmt.Println("\t\t\t\t3 信息列表")
		fmt.Println("\t\t\t\t4 退出")
		fmt.Println("\t\t\t\t 请选择(1-4):")
		var key int
		var content string
		fmt.Scanf("%d\n", &key)
		switch key {
		case 1:
			userManagerProcess.OutputOnlineFriends()
		case 2:
			fmt.Println("你想对大家说点什么？")
			fmt.Scanf("%s\n", &content)
			smsProcess.SendGroupMsg(content)
		case 3:
			smsProcess.OutputAllMsg()
		case 4:
			fmt.Println("退出登陆")
			loop = false
		default:
			fmt.Println("输入错误，请重新输入")
		}
	}

}

// ServerProcessMsg 和服务器端保持通讯
func ServerProcessMsg(conn netWork.Conn) {
	for {
		//fmt.Println("客户端正在等待读取服务器发送的消息")
		msg, err := conn.Get()
		if err != nil {
			fmt.Println("读取服务器发送的消息失败, err:", err)
			return
		}
		//fmt.Println("读取到了服务器的信息, msg: ", msg)
		switch msg.Type {
		case constants.MSG_TYPE_NOTIFY_USER_STATUS:
			notifyStatusMsg := message.SrvMsgNotifyUserStatus{}
			err = json.Unmarshal([]byte(msg.Data), &notifyStatusMsg)
			if err != nil {
				fmt.Println("更新在线用户失败：", err.Error())
				return
			}
			userManagerProcess.UpdateOnlineUser(notifyStatusMsg.UserId, notifyStatusMsg.UserStatus)
		case constants.MSG_TYPE_NOTIFY_NEW_FRIEND:
			notifyNewFriendMsg := message.SrvMsgNotifyNewFriend{}
			err = json.Unmarshal([]byte(msg.Data), &notifyNewFriendMsg)
			if err != nil {
				fmt.Println("添加好友失败：", err.Error())
				return
			}
			userManagerProcess.AddFriends(notifyNewFriendMsg.UserId, notifyNewFriendMsg.UserName)
		case constants.MSG_TYPE_SMS_MSG_FORWARD:
			smsMsg := message.SmsMsg{}
			err = json.Unmarshal([]byte(msg.Data), &smsMsg)
			if err != nil {
				fmt.Println("收取消息失败：", err.Error())
				return
			}
			smsProcess.ReceiveMsg(smsMsg)
		default:
			fmt.Println("服务器返回了无法处理的消息类型")
		}

	}
}
